package com.fy.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
    //读取cookie
    public static String getCookie(String name, HttpServletRequest req) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    //写入cookie
    public static void setCookie(String name, String value, HttpServletResponse resp,Boolean delete) {
        Cookie cookie = new Cookie(name, value);

        cookie.setPath("/");
        if (delete){
            cookie.setMaxAge(0);
        }
        resp.addCookie(cookie);
    }

    public static void setUserToken2Cookie(String name, String value, HttpServletResponse resp){
        setCookie(name,value,resp,false);
    }


    public static void deleteUserTokenFromCookie(String name,HttpServletResponse response){
        setCookie(name,null,response,true);
    }

    //
}
